package com.ym.core.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import com.ym.core.config.ConfigCenterProperties;
import com.ym.core.config.JpushConfig;
import com.ym.medical.domain.bo.PushBean;
import com.ym.medical.domain.bo.PushBeanExtraVo;
import com.ym.medical.domain.entity.JpushAccountEntity;
import com.ym.medical.domain.entity.UserEntity;
import com.ym.medical.enums.JpushAccountType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 推送服务
 * 封装业务功能相关
 */
public class JPushUtil {

	private final static Logger logger = LoggerFactory.getLogger(JPushUtil.class);

	/**
	 * 配置中心
	 */
	private static final JpushConfig pushConfig = SpringUtil.getBean(ConfigCenterProperties.class).getPushConfig();

	/**
	 * 推送客戶端
	 */
	private static JPushClient jPushClient;

	static {
		jPushClient = new JPushClient(pushConfig.getSecret(), pushConfig.getAppkey());
	}


	/**
	 * 剔除无效registed
	 *
	 * @param registids
	 * @return
	 * @author YangJie [2016年7月15日 下午4:03:31]
	 */
	private static String[] checkRegistids(String[] registids) {
		List<String> regList = new ArrayList<String>(registids.length);
		for (String registid : registids) {
			if (registid != null && !"".equals(registid.trim())) {
				regList.add(registid);
			}
		}
		return regList.toArray(new String[0]);
	}

	/**
	 * 广播,业务相关
	 *
	 * @param pushBean
	 * @param jpushAccounts
	 */
	public static void pushAll(PushBean pushBean, List<JpushAccountEntity> jpushAccounts) {
		for (JpushAccountEntity jpushAccount : jpushAccounts) {
			if (jpushAccount.getType().equals(JpushAccountType.APPLE.getKey())) {
				JPushUtil.pushIos(pushBean, jpushAccount.getAccount());
			} else {
				JPushUtil.pushAndroid(pushBean, jpushAccount.getAccount());
			}
		}
	}

	/**
	 * 广播,业务相关
	 *
	 * @param pushBean
	 * @param jpushAccounts
	 */
	public static void pushAllAlias(PushBean pushBean, List<JpushAccountEntity> jpushAccounts) {
		for (JpushAccountEntity jpushAccount : jpushAccounts) {
			if (jpushAccount.getType().equals(JpushAccountType.APPLE.getKey())) {
				JPushUtil.pushIosAlias(pushBean, jpushAccount.getUserId().toString());
			} else {
				JPushUtil.pushAndroidAlias(pushBean, jpushAccount.getUserId().toString());
			}
		}
	}

	/**
	 * 广播 (所有平台，所有设备, 不支持附加信息)
	 *
	 * @param pushBean 推送内容
	 * @return
	 * @author YangJie [2016年6月17日 下午4:12:08]
	 */
	public static boolean pushAll(PushBean pushBean) {
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.all())
				.setAudience(Audience.all())
				.setNotification(Notification.alert(pushBean.getAlert()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}

	/**
	 * ios广播
	 *
	 * @param pushBean 推送内容
	 * @return
	 * @author YangJie [2016年6月17日 下午3:59:21]
	 */
	public static boolean pushAllIos(PushBean pushBean) {
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.all())
				.setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}

	/**
	 * ios通过registid推送 (一次推送最多 1000 个)
	 *
	 * @param pushBean  推送内容
	 * @param registids 推送id
	 * @return
	 * @author YangJie [2016年6月17日 下午3:59:21]
	 */
	public static boolean pushIos(PushBean pushBean, String... registids) {
		registids = checkRegistids(registids);
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.registrationId(registids))
				.setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}

	/**
	 * ios通过registid推送 (一次推送最多 1000 个)
	 *
	 * @param pushBean  推送内容
	 * @param registids 推送id
	 * @return
	 * @author YangJie [2016年6月17日 下午3:59:21]
	 */
	public static boolean pushIosAlias(PushBean pushBean, String... registids) {
		registids = checkRegistids(registids);
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.alias(registids))
				.setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}


	/**
	 * android广播
	 *
	 * @param pushBean 推送内容
	 * @return
	 * @author YangJie [2016年6月17日 下午3:59:21]
	 */
	public static boolean pushAllAndroid(PushBean pushBean) {
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.android())
				.setAudience(Audience.all())
				.setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}

	/**
	 * android通过registid推送 (一次推送最多 1000 个)
	 *
	 * @param pushBean  推送内容
	 * @param registids 推送id
	 * @return
	 * @author YangJie [2016年6月17日 下午3:59:21]
	 */
	public static boolean pushAndroid(PushBean pushBean, String... registids) {
		registids = checkRegistids(registids);
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.android())
				.setAudience(Audience.registrationId(registids))
				.setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}

	/**
	 * android通过registid推送 (一次推送最多 1000 个)
	 *
	 * @param pushBean  推送内容
	 * @param registids 推送id
	 * @return
	 * @author YangJie [2016年6月17日 下午3:59:21]
	 */
	public static boolean pushAndroidAlias(PushBean pushBean, String... registids) {
		registids = checkRegistids(registids);
		return sendPush(PushPayload.newBuilder()
				.setPlatform(Platform.android())
				.setAudience(Audience.alias(registids))
				.setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
				.setOptions(Options.newBuilder().setApnsProduction(pushConfig.isApns()).build())
				.build());
	}

	/**
	 * 调用api推送
	 *
	 * @param pushPayload 推送实体
	 * @return
	 * @author YangJie [2016年6月17日 下午4:19:03]
	 */
	private static boolean sendPush(PushPayload pushPayload) {
		logger.info("发送极光推送请求: {}", JSONObject.toJSONString(pushPayload));
		PushResult result = null;
		try {
			result = jPushClient.sendPush(pushPayload);
		} catch (APIConnectionException e) {
			logger.error("极光推送连接异常: ", e);
		} catch (APIRequestException e) {
			logger.error("极光推送请求异常: ", e);
		}
		if (result != null && result.isResultOK()) {
			logger.info("极光推送请求成功: {}", result);
			return true;
		} else {
			logger.info("极光推送请求失败: {}", result);
			return false;
		}
	}

	/**
	 * 通过PUshbean返回要显示的内容
	 *
	 * @param pushBean
	 * @return
	 */
	public static String getMessageByPushBean(PushBean pushBean) {
		PushBeanExtraVo extrasBean = pushBean.getExtrasBean();
		String msgTypeParent = extrasBean.getMsgTypeParent();
		String msgTypeSub = extrasBean.getMsgTypeSub();
		UserEntity pushWho = extrasBean.getPushWho();
		UserEntity whoPush = extrasBean.getWhoPush();
		String status = extrasBean.getStatus();
		String statusName = null;
		String msg = null;
		if ("01".equals(msgTypeParent)) {
			//系统消息
			switch (msgTypeSub) {
				case "01":
					//资质审核消息 03 04
					statusName = "03".equals(status) ? "审核通过" : "审核不通过";
					msg = String.format("%s您的资质认证%s", pushWho.getRealName(),statusName);
					break;
			}
		} else if ("02".equals(msgTypeParent)) {
			//工作室消息
			switch (msgTypeSub) {
				case "01":
					//申请加入工作室审核消息
					statusName = "02".equals(status) ? "拒绝" : "通过";
					msg = String.format("%s，您加入%s医生工作室的申请已被%s！", pushWho.getRealName(), whoPush.getRealName(), statusName);
					break;
				case "02":
					//申请加入工作室消息
					msg = String.format("%s申请加入您的工作室！", whoPush.getRealName());
					break;
				case "03":
					//申请开通服务项消息
					msg = String.format("%s申请开通工作室的服务项！", whoPush.getRealName());
					break;
				case "04":
					//开通工作室审核消息
					statusName = "02".equals(status) ? "拒绝" : "通过";
					msg = String.format("%s，您的工作室申请已被%s！", pushWho.getRealName(), statusName);
					break;
				case "05":
					//邀请加入工作室消息
					msg = String.format("%s,%s医生邀请您加入工作室！", pushWho.getRealName(), whoPush.getRealName());
					break;
				case "06":
					//邀请开通服务项消息
					msg = String.format("%s,%s医生邀请您开通服务项！", pushWho.getRealName(), whoPush.getRealName());
					break;
				case "07":
					//邀请加入工作室审核消息
					statusName = "02".equals(status) ? "被拒绝" : "通过";
					msg = String.format("%s，您邀请%s医生加入工作室已%s！", pushWho.getRealName(), whoPush.getRealName(), statusName);
					break;
			}
		} else if ("03".equals(msgTypeParent)) {
			//问诊消息
			switch (msgTypeSub) {
				case "01":
					//单人图文咨询
					msg = String.format("%s,您有一条来自%s的电话咨询！请注意查看", pushWho.getRealName(), whoPush.getRealName());
					break;
				case "02":
					//单人电话咨询
					msg = String.format("%s,您有一条来自%s的图文咨询！请注意查看", pushWho.getRealName(), whoPush.getRealName());
					break;
				case "03":
					//单人视频咨询
					msg = String.format("%s,您有一条来自%s的视频咨询！请注意查看", pushWho.getRealName(), whoPush.getRealName());
					break;
				case "04":
					//工作室图文问诊消息
					//msg = String.format("%s，%s向您发来求助！快去看看吧！", pushWho.getRealName(), whoPush.getRealName());
					msg = String.format("工作室来新单子了！快去看看吧！", pushWho.getRealName(), whoPush.getRealName());
					break;
			}

		} else if ("04".equals(msgTypeParent)) {
			//通讯录消息

		}
		logger.info("发送推送消息 ：{}", msg);
		return msg;
	}
}
